package com.hujf.flink.window;

import com.hujf.flink.stock.StockPrice;
import com.hujf.flink.stock.StockSource;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @Author hujf
 * @Date 2022/5/11 14:48
 * @Description TODO
 */
public class WindowAssignerTest {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();
        StockSource stockSource = new StockSource("stock");
        DataStreamSource<StockPrice> stockPriceDataStreamSource = environment.addSource(stockSource);

        SingleOutputStreamOperator<Tuple2<String, Long>> reduce = stockPriceDataStreamSource.flatMap(new FlatMapFunction<StockPrice, Tuple2<String, Long>>() {
                    @Override
                    public void flatMap(StockPrice value, Collector<Tuple2<String, Long>> out) throws Exception {
                        out.collect(new Tuple2<>(value.getSymbol(),value.getVolume()));
                    }
                }).keyBy(value -> value.f0).reduce(new ReduceFunction<Tuple2<String, Long>>() {
            @Override
            public Tuple2<String, Long> reduce(Tuple2<String, Long> value1, Tuple2<String, Long> value2) throws Exception {
                return new Tuple2(value1.f0, value1.f1 + value2.f1);
            }
        });

        reduce.print();
        environment.execute();
    }
}
